package com.whty.cms.filewps.upload.controller;


import com.whty.cms.filewps.common.constants.Consts;
import com.whty.cms.filewps.common.message.ResponseMessage;
import com.whty.cms.filewps.common.model.EsAttachment;
import com.whty.cms.filewps.common.service.CmqService;
import com.whty.cms.filewps.common.service.ICosService;
import com.whty.cms.filewps.config.dto.ApplyInfo;
import com.whty.cms.filewps.config.service.IApplyInfoService;
import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.dto.TransformJob;
import com.whty.cms.filewps.upload.service.IUploadService;
import com.whty.cms.filewps.upload.service.IVersionService;
import com.whty.cms.filewps.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.util.UriEncoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@CrossOrigin(origins = "*",maxAge = 3600)
@Controller
@RequestMapping(value = {"/wps"})
public class UploadController {

	private static final Logger logger = LogManager.getLogger(UploadController.class);

	@Autowired
	private IUploadService uploadService;

	@Autowired
	private ICosService cosService;

	@Autowired
	private IVersionService versionService;

	@Autowired
	private IApplyInfoService applyInfoService;


	@RequestMapping(value = "/getEditUrl", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getEditUrl(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();
		String fileExt;
		String fileName;
		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(String.valueOf(attach.getFid()))) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			JSONObject json = EsUtil.searchDoc(String.valueOf(attach.getFid()));
			fileExt = json.optString("fileExt");
			attach.setFileExt(fileExt);

			if(StringUtils.isBlank(attach.getFileName())){
				fileName = json.optString("fileName");
				attach.setFileName(fileName);
			}else{
				fileName = attach.getFileName();
				if(!fileExt.equals(fileName.substring(fileName.lastIndexOf(".") + 1))){
					fileName = fileName+"."+fileExt;
					attach.setFileName(fileName);
				}
			}
			String url = WPSEdit.getEditUrl(attach);
			return returnMessage(result, "000000","成功",url );
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误",e.getMessage() );
		}
	}

	@RequestMapping(value = "/getCooperators", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getCooperators(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();

		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(String.valueOf(attach.getFid()))) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			//JSONArray array = WPSEdit.getCooperators(String.valueOf(attach.getFid()));
			cn.hutool.json.JSONArray userArr = new cn.hutool.json.JSONArray();
			cn.hutool.json.JSONObject userJson1 = new cn.hutool.json.JSONObject();
			userJson1.put("id","a7e33f16f00511eb9b1a020315540695");
			userJson1.put("name","胡灿");
			userJson1.put("permission","write");
			userJson1.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/common/images/nophoto_mid.gif?_r=1675925646");

			cn.hutool.json.JSONObject userJson2 = new cn.hutool.json.JSONObject();
			userJson2.put("id","0b2ad34c934911eab65a020315ff211d");
			userJson2.put("name","代昌盛");
			userJson2.put("permission","write");
			userJson2.put("avatar_url","https://css.huijiaoyun.com/tianyu_edu/common/images/nophoto_mid.gif?_r=1675925773");

			userArr.add(userJson1);
			userArr.add(userJson2);
			return returnMessage(result, "000000","成功",userArr );
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误",e.getMessage() );
		}
	}


	@RequestMapping(value = "/refresh", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage refresh(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();

		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(String.valueOf(attach.getFid()))) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			result = WPSEdit.refresh(String.valueOf(attach.getFid()));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误",e.getMessage() );
		}
	}


	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage save(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();

		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(String.valueOf(attach.getFid()))||StringUtils.isBlank(attach.getFileExt())) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			result = WPSEdit.save(String.valueOf(attach.getFid()),attach.getFileExt());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误",e.getMessage() );
		}
	}


	@RequestMapping(value = "/getpreviewUrl", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getpreviewUrl(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();

		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(String.valueOf(attach.getFid()))) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			JSONObject json = EsUtil.searchDoc(String.valueOf(attach.getFid()));
			attach.setFileExt(json.optString("fileExt"));
			String url = WPSEdit.getpreviewUrl(attach);
			return returnMessage(result, "000000","成功",url );
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误",e.getMessage() );
		}
	}

	//获取文件最新版本预览地址
	@RequestMapping(value = "/getNewPreview/{fid}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage updateAttachForCMS(@PathVariable String fid) throws Exception {
		ResponseMessage result = new ResponseMessage();
		String url = "http://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + fid;
		Map<String, String> map = MapUtil.newHashMap();
		String newFid = versionService.getNewFid(fid);

		if(newFid!=null) {
			url = "http://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + newFid;
		}
		String respone = new HttpClient(url).doGet();
		JSONObject j = JSONObject.fromObject(respone);
		if ("000000".equals(j.getString("code"))) {
			JSONObject data1 = j.getJSONObject("data");

			if (org.apache.commons.lang3.StringUtils.isNotBlank(data1.getString("previewUrl"))) {
				String previewUrl = data1.getString("previewUrl");
				map.put("previewUrl",previewUrl);
			}
			if (org.apache.commons.lang3.StringUtils.isNotBlank(data1.getString("downloadUrl"))) {
				String downUrl = data1.getString("downloadUrl");
				map.put("downUr",downUrl);
			}
		}
		return returnMessage(result, "000000","成功",map);
	}

	@RequestMapping(value = "/initiateMultipartUpload", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage initiateMultipartUpload(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();
		Map<String, Object> map = MapUtil.newHashMap();
		if(StringUtils.isBlank(attach.getFileMd5())||StringUtils.isBlank(attach.getFileName())||
				StringUtils.isBlank(attach.getUserId())||StringUtils.isBlank(attach.getFileLength().toString())||
				StringUtils.isBlank(attach.getApplyType())) {
			return returnMessage(result, "100000","必填参数为空","" );
		}
		if("b49ac4183f1311e9bcfd00fec0a8c9c9".equals(attach.getApplyType())&&StringUtils.isBlank(attach.getPlatformCode())) {
			return returnMessage(result, "100000","云平台的平台编码参数不能为空","" );
		}
		try {
			long t0 = System.currentTimeMillis();
			map = cosService.initiateMultipartUpload(attach);
			long t1 = System.currentTimeMillis();
			logger.info("初始化分片上传花费时间=" + (t1 - t0));
			return returnMessage(result, "000000","成功",map );
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return returnMessage(result, "400000","系统内部错误","" );
		}
	}

	@RequestMapping(value = "/getTempCredential", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage getTempCredential(String appId, @RequestParam(value="region", required=false, defaultValue = "") String region) {
		ResponseMessage result = new ResponseMessage();
		if(StringUtils.isBlank(appId)) {
			return returnMessage(result, "100000","必填参数为空","" );
		}
		if(StringUtils.isBlank(region)) {
			region = "ap-shanghai";
		}
		try {
			long t0 = System.currentTimeMillis();
			String bucketName = MemcacheUtil.getDatabaseObj(appId+"-"+Consts.SOURCE_BUCKET);
			Map<String, String> tempMap = (Map<String, String>) MemcacheUtil.getObj(bucketName+region+"TempCredential");
			if(null!=tempMap) {
				return returnMessage(result, "000000","获取成功",tempMap );
			}else {
				Map<String, String> map = MapUtil.newHashMap();
				map = cosService.getTempCredential(bucketName,region);
				long t1 = System.currentTimeMillis();
				logger.info("获取密钥时间为==" + (t1 - t0));
				return returnMessage(result, "000000","获取成功",map );
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return returnMessage(result, "400000","系统内部错误","" );
		}
	}

	@RequestMapping(value = "/getPartCosAuthorization", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getPartCosAuthorization(@RequestBody JSONObject object) {
		ResponseMessage result = new ResponseMessage();
		Map<String, Object> map = MapUtil.newHashMap();
		try {
			String sign = cosService.getPartCosAuthorization(object);
			map.put("authorization", sign);
			return returnMessage(result, "000000","获取成功",map );
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return returnMessage(result, "400000","系统内部错误","" );
		}
	}

	@RequestMapping(value = "/getSimpleCosAuthorization", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getSimpleCosAuthorization(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();
		Map<String, Object> map = MapUtil.newHashMap();
		try {
			if(StringUtils.isBlank(attach.getUserId())||StringUtils.isBlank(attach.getFileName())
					||StringUtils.isBlank(attach.getApplyType())) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if("b49ac4183f1311e9bcfd00fec0a8c9c9".equals(attach.getApplyType())&&StringUtils.isBlank(attach.getPlatformCode())) {
				return returnMessage(result, "100000","云平台的平台编码参数不能为空","" );
			}
			map = cosService.getSimpleCosAuthorization(attach);
			return returnMessage(result, "000000","获取成功",map );
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return returnMessage(result, "400000","系统内部错误","" );
		}
	}

	@RequestMapping(value = "/completeMultipartUpload", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage completeMultipartUpload(@RequestBody AttachFile attach) {
		ResponseMessage result = new ResponseMessage();
		Map<String, Object> map = MapUtil.newHashMap();
		try {
			if(null==attach) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			if(StringUtils.isBlank(attach.getFilePath())||StringUtils.isBlank(attach.getUploadId())
					||StringUtils.isBlank(attach.getFileName())||StringUtils.isBlank(String.valueOf(attach.getFileLength()))
					||StringUtils.isBlank(attach.getFileMd5())||StringUtils.isBlank(attach.getSourceType())
					||StringUtils.isBlank(attach.getApplyType())||StringUtils.isBlank(attach.getUserId())||StringUtils.isBlank(attach.getPlatformCode())) {
				return returnMessage(result, "100000","必填参数为空","" );
			}
			ApplyInfo applyInfo = applyInfoService.findOneById(attach.getApplyType());
			if(applyInfo == null) {
				return returnMessage(result, "100000","applyType校验失败","" );
			}
			String transFormFlag = applyInfo.getTransformFlag();
			if(StringUtils.isBlank(attach.getNeedTransform())) {
				attach.setNeedTransform("1");  //默认需要转码
			}
			//应用类型初始化不需要转码
			if(StringUtils.isNotBlank(transFormFlag) && transFormFlag.equals("1")) {
				attach.setNeedTransform("0");  //设置不需要转码
			}
			long t0 = System.currentTimeMillis();
			map = cosService.completeMultipartUpload(attach);
			long t1 = System.currentTimeMillis();
			logger.info("上传完成花费时间=" + (t1 - t0));
			return returnMessage(result, "000000","成功",map );
		} catch (Exception e) {
			logger.error(e.getMessage());
			return returnMessage(result, "400000","系统内部错误","" );
		}
	}

	@RequestMapping(value = "/getAttachFileByFid/{fid}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage getAttachFileByFid(@PathVariable String fid) throws Exception {
		ResponseMessage result = new ResponseMessage();
		Map<String, Object> map = MapUtil.newHashMap();
		String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
		if(StringUtils.isBlank(fid)) {
			return returnMessage(result, "100000","必填参数为空","" );
		}
		JSONObject json = EsUtil.searchDoc(fid);

		if(json.isEmpty()) {
			return returnMessage(result, "500001","fid无效，对应的文件不存在","" );
		}
		String customDestUrl =(String) MemcacheUtil.getObj(json.optString("applyType")+"-customDestBucket");
		String customSourceUrl =(String)  MemcacheUtil.getObj(json.optString("applyType")+"-customSourceBucket");
		String sourceBucket = (String)MemcacheUtil.getObj(json.optString("applyType") + "-sourceBucket");

		map.put("fid", json.optString("fid"));
		String duration = json.getString("duration");
		String fileLength = json.getString("fileLength");
		String downloadUrl = json.optString("downloadUrl");
		String previewUrl = json.optString("previewUrl");
		String thumbnailUrl = json.optString("thumbnailUrl");
		String bucketName = json.optString("bucketName");
		if(StringUtils.isBlank(bucketName)) {
			return returnMessage(result, "510000","数据不完整，请联系管理员",map );
		}
		if("0".equals(MemcacheUtil.getDatabaseObj(bucketName))) {//私有桶获取的地址代签名
			downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(json.optString("filePath"), json.optString("applyType"));
			if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
				if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
						previewUrl = WPSUtil.getpreviewUrl(fid);
						json.put("previewUrl",previewUrl);
						EsUtil.addOrUpdateDoc(String.valueOf(fid), json.toString());
					}
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
				}else if("cos".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(json.optString("filePath")), json.optString("applyType"))+"&ci-process=doc-preview&dstType=html";
				}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
				}
			}
		}else {
			if(downloadUrl.indexOf(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"))>-1) {
				downloadUrl = UriEncoder.encode(downloadUrl);
				downloadUrl = downloadUrl.replace(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"), cdnUrl);
			}
			if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
				if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
						previewUrl = WPSUtil.getpreviewUrl(fid);
						json.put("previewUrl",previewUrl);
						EsUtil.addOrUpdateDoc(fid, json.toString());
					}
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
				}else if("cos".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(json.optString("filePath")), json.optString("applyType"))+"&ci-process=doc-preview&dstType=html";
				}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
				}
			}
		}
		//预览地址和下载地址替换cdn域名
		downloadUrl = downloadUrl.replace(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"), cdnUrl);

		//下载地址替换自定义域名
		if(StringUtils.isNotBlank(customSourceUrl)&& !downloadUrl.startsWith(customSourceUrl)){
			downloadUrl = downloadUrl.replace(downloadUrl.substring(0,downloadUrl.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
		}

		downloadUrl = downloadUrl.replace("http:","https:");

		if("222400".equals(json.optString("platformCode"))||"220000".equals(json.optString("platformCode"))){
			downloadUrl = downloadUrl.replace("https:","http:");
		}
		map.put("downloadUrl", downloadUrl);

		if(StringUtils.isNotBlank(previewUrl)) {
			previewUrl = previewUrl.replace(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"), cdnUrl);
			previewUrl = previewUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), cdnUrl);
		}

		thumbnailUrl = thumbnailUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), cdnUrl);
		if(previewUrl.startsWith("http://null")) {
			previewUrl = previewUrl.replace("http://null", "http://test-rc-dest-1256736654");
		}
		//家校帮的资源并且是mp3格式或者mp4格式返回的预览地址为下载地址
		if(StringUtils.isBlank(previewUrl)&&"fc999a39373d4ef486064f67d46c5275".equals(json.optString("applyType"))&&("mp3".equals(json.optString("fileExt").toLowerCase())||"mp4".equals(json.optString("fileExt").toLowerCase()))) {
			previewUrl = downloadUrl;
		}
		//自定义域名不为空的话，修改预览地址和下载为自定义域名，图片和视频预览地址的桶名不一样
		//吉林延边资源音视频文件没有转码，所以没有缩略图
		replacePreviewUrl(map,thumbnailUrl,previewUrl,json.optString("fileExt").toLowerCase(),cdnUrl,customDestUrl,customSourceUrl,sourceBucket,json.optString("applyType").toLowerCase());


		map.put("duration", duration);
		map.put("fileLength", fileLength);
		map.put("fileExt", json.optString("fileExt"));
		map.put("userId", json.optString("userId"));
		map.put("fileMd5", json.optString("fileMd5"));
		map.put("fileName", json.optString("fileName"));
		return returnMessage(result, "000000","成功",map );
	}


	@RequestMapping(value = "/getAttachFileByFids", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getAttachFileByFids(@RequestBody JSONObject object) throws Exception {
		ResponseMessage result = new ResponseMessage();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String fids = object.optString("fids");
		if(StringUtils.isBlank(fids)) {
			return returnMessage(result, "100000","必填参数为空","" );
		}
		String[] fidList = fids.split(",");
		for(int i=0;i<fidList.length;i++) {
			Map<String, Object> map = MapUtil.newHashMap();
			String fid = fidList[i];
			if(StringUtils.isNotBlank(fid)) {
				JSONObject json = EsUtil.searchDoc(fid);
				if(json.isEmpty()) {
					return returnMessage(result, "500001","fid无效，对应的文件不存在","" );
				}
				map.put("fid", json.optString("fid"));
				String duration = json.getString("duration");
				String fileLength = json.getString("fileLength");
				String downloadUrl = json.optString("downloadUrl");
				String previewUrl = json.optString("previewUrl");;
				String thumbnailUrl = json.optString("thumbnailUrl");
				if("0".equals(MemcacheUtil.getDatabaseObj(json.optString("bucketName")))) {
					downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(json.optString("filePath"), json.optString("applyType"));
					if(Consts.audioList.contains(json.optString("fileExt").toLowerCase())||Consts.videoList.contains(json.optString("fileExt").toLowerCase())) {
						if(StringUtils.isNotBlank(previewUrl)) {
							previewUrl = CosUtil.getAuthPreviewUrl(previewUrl.substring(previewUrl.indexOf("myqcloud.com")+12, previewUrl.length()), json.optString("applyType"));
						}
						if(StringUtils.isNotBlank(thumbnailUrl)) {
							thumbnailUrl = CosUtil.getAuthPreviewUrl(thumbnailUrl.substring(thumbnailUrl.indexOf("myqcloud.com")+12, thumbnailUrl.length()), json.optString("applyType"));
						}
					}else if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
						if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
								previewUrl = WPSUtil.getpreviewUrl(fid);
								json.put("previewUrl",previewUrl);
								EsUtil.addOrUpdateDoc(fid, json.toString());
							}
						}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
						}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
						}else{
							previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
						}
					}else if(Consts.picList.contains(json.optString("fileExt").toLowerCase())||Consts.movieList.contains(json.optString("fileExt").toLowerCase())||"mp3".equals(json.optString("fileExt").toLowerCase())) {
						previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(json.optString("filePath")), json.optString("applyType"));
					}
				}else {
					if(Consts.picList.contains(json.optString("fileExt").toLowerCase())||Consts.movieList.contains(json.optString("fileExt").toLowerCase())||"mp3".equals(json.optString("fileExt").toLowerCase())) {
						previewUrl = "http://"+MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-"+Consts.SOURCE_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint")+CosUtil.getCorrectKey(json.optString("filePath"));
					}
					if(downloadUrl.indexOf(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"))>-1) {
						downloadUrl = UriEncoder.encode(downloadUrl);
					}
					thumbnailUrl = UriEncoder.encode(thumbnailUrl);
					if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
						if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
								previewUrl = WPSUtil.getpreviewUrl(fid);
								json.put("previewUrl",previewUrl);
								EsUtil.addOrUpdateDoc(String.valueOf(fid), json.toString());
							}
						}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
						}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
							previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
						}else{
							previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
						}

					}else {
						previewUrl = UriEncoder.encode(previewUrl);
					}
				}
				map.put("downloadUrl", downloadUrl);
				if(StringUtils.isNotBlank(previewUrl)) {
					previewUrl = previewUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
				}
				if(previewUrl.startsWith("http://null")) {
					previewUrl = previewUrl.replace("http://null", "http://test-rc-dest-1256736654");
				}
				//家校帮的资源并且是mp3格式或者mp4格式返回的预览地址为下载地址
				if("fc999a39373d4ef486064f67d46c5275".equals(json.optString("applyType"))&&("mp3".equals(json.optString("fileExt").toLowerCase())||"mp4".equals(json.optString("fileExt").toLowerCase()))) {
					previewUrl = downloadUrl;
				}
				map.put("previewUrl", previewUrl);
				thumbnailUrl = thumbnailUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
				if(thumbnailUrl.startsWith("http://null")) {
					thumbnailUrl = thumbnailUrl.replace("http://null", "http://test-rc-dest-1256736654");
				}
				if(Consts.docList.contains(json.optString("fileExt").toLowerCase())&&"office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
				}
				map.put("previewUrl", previewUrl);
				thumbnailUrl = thumbnailUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
				map.put("thumbnailUrl", thumbnailUrl);
				map.put("duration", duration);
				map.put("fileLength", fileLength);
				list.add(map);
			}
		}

		return returnMessage(result, "000000","成功",list );
	}

	@RequestMapping(value = "/getTransformInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage getTransformInfo(@RequestBody JSONObject jsons) {
		ResponseMessage result = new ResponseMessage();
		List<String> EventHandleList = new ArrayList<>();
		JSONArray jsonArr = jsons.getJSONArray("EventSet");
		try {
			for(int i=0;i<jsonArr.size();i++) {
				JSONObject json = jsonArr.getJSONObject(i);
				String eventType = json.optString("EventType");
				logger.info("视频转码完成后的回调============》"+eventType+",EventHandle======"+json.optString("EventHandle"));
				if("ProcedureStateChanged".equals(eventType)) {
					JSONObject data = json.optJSONObject("ProcedureStateChangeEvent");
					long code = data.optLong("ErrCode");      //错误码。0：成功，其他值：失败
					String status = data.optString("Status"); //任务流状态，有 PROCESSING 和 FINISH 两种
					if(code==0) {
						if("FINISH".equals(status)) {
							try {
    							/*boolean flag = uploadService.saveTransformInfo(data);
    							if(flag) {
    								EventHandleList.add(json.optString("EventHandle"));
    							}*/
								//只要转码成功，就确认消费，避免很多没有关联上的transformId因为在es找不到数据，无法消费，导致队列积压
								uploadService.saveTransformInfo(data);
								EventHandleList.add(json.optString("EventHandle"));
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}else {
						logger.error("转码失败====》"+code);
						EventHandleList.add(json.optString("EventHandle"));
					}
				}
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return returnMessage(result, "000000","成功",EventHandleList );
	}


	@RequestMapping(value="/viewHtml5ByFid.html" , method = RequestMethod.GET)
	public String viewHtml5ByFid(HttpServletRequest request) throws Exception {
		Map<String, Object> map = MapUtil.newHashMap();
		String fid = request.getParameter("fid");
		String playWidth = request.getParameter("playWidth");
		String playHeight = request.getParameter("playHeight");
		if(StringUtils.isBlank(playWidth)) {
			playWidth = "765";
		}
		if(StringUtils.isBlank(playHeight)) {
			playHeight = "600";
		}
		JSONObject json = EsUtil.searchDoc(fid);
		String previewUrl = json.optString("previewUrl");
		if("0".equals(MemcacheUtil.getDatabaseObj(json.optString("bucketName")))) {
			if(Consts.audioList.contains(json.optString("fileExt").toLowerCase())||Consts.videoList.contains(json.optString("fileExt").toLowerCase())) {
				if(StringUtils.isNotBlank(previewUrl)) {
					previewUrl = CosUtil.getAuthPreviewUrl(previewUrl.substring(previewUrl.indexOf("myqcloud.com")+12, previewUrl.length()), json.optString("applyType"));
				}
			}else if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
				if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
						previewUrl = WPSUtil.getpreviewUrl(fid);
						json.put("previewUrl",previewUrl);
						EsUtil.addOrUpdateDoc(String.valueOf(fid), json.toString());
					}
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
				}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(json.optString("downloadUrl"));
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
				}
			}else if(Consts.picList.contains(json.optString("fileExt").toLowerCase())||Consts.movieList.contains(json.optString("fileExt").toLowerCase())||"mp3".equals(json.optString("fileExt").toLowerCase())||"swf".equals(json.optString("fileExt").toLowerCase())) {
				previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(json.optString("filePath")), json.optString("applyType"));
			}
		}else {
			if(Consts.picList.contains(json.optString("fileExt").toLowerCase())||Consts.movieList.contains(json.optString("fileExt").toLowerCase())||"mp3".equals(json.optString("fileExt").toLowerCase())||"swf".equals(json.optString("fileExt").toLowerCase())) {
				previewUrl = "http://"+MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-"+Consts.SOURCE_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint")+CosUtil.getCorrectKey(json.optString("filePath"));
			}else if(Consts.docList.contains(json.optString("fileExt").toLowerCase())){
				if("linux".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					if(previewUrl.indexOf("fc-wpslinux")<0||previewUrl.indexOf("AK20211227QHIFNR")>0){
						previewUrl = WPSUtil.getpreviewUrl(fid);
						json.put("previewUrl",previewUrl);
						EsUtil.addOrUpdateDoc(String.valueOf(fid), json.toString());
					}
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(fid,json.optString("fileExt").toLowerCase());
				}else if("office365".equals(MemcacheUtil.getDatabaseObj(json.optString("applyType")+"-previewVersion"))){
					previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(json.optString("downloadUrl"));
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+fid;
				}
			}
		}
		if(previewUrl.startsWith("http://")) {
			previewUrl = previewUrl.replace("http://", "https://");
		}
		if(StringUtils.isBlank(previewUrl)) {
			//预览地址为null 设置为下载地址
			previewUrl = json.optString("downloadUrl");
		}
		previewUrl = previewUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
		String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
		String customDestUrl = (String) MemcacheUtil.getObj(json.optString("applyType") + "-customDestBucket");
		String customSourceUrl = (String) MemcacheUtil.getObj(json.optString("applyType") + "-customSourceBucket");
		String sourceBucket = (String)MemcacheUtil.getObj(json.optString("applyType") + "-sourceBucket");
		//预览地址替换cdn自定义域名
		replacePreviewUrl(map,"",previewUrl,json.optString("fileExt").toLowerCase(),cdnUrl,customDestUrl,customSourceUrl,sourceBucket,json.optString("applyType"));

		previewUrl = (String)map.get("previewUrl");
		request.setAttribute("previewUrl", previewUrl);
		String fileExt = json.optString("fileExt");
		EsAttachment es = new EsAttachment();
		es.setFileExt(fileExt);
		String fileExtType = es.getFileExtType();
		request.setAttribute("fileExt", fileExt);
		request.setAttribute("fileExtType", fileExtType);
		request.setAttribute("playWidth", playWidth);
		request.setAttribute("playHeight", playHeight);
		return "upload/viewHtml5ByFid.html";
	}



	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public String download(HttpServletRequest request) {
		Long start = System.currentTimeMillis();
		String fid = request.getParameter("fid");
		if(StringUtils.isBlank(fid)) {
			return "必填参数为空";
		}
		JSONObject json = EsUtil.searchDoc(fid);
		if(json.isEmpty()) {
			return "fid无效，对应的文件不存在";
		}
		String downloadUrl = json.optString("downloadUrl");
		String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
		String customDestUrl = (String) MemcacheUtil.getObj(json.optString("applyType") + "-customDestBucket");
		String customSourceUrl = (String) MemcacheUtil.getObj(json.optString("applyType") + "-customSourceBucket");
		if("0".equals(MemcacheUtil.getDatabaseObj(json.optString("bucketName")))) {
			downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(json.optString("filePath"), json.optString("applyType"));
		}else {
			if(downloadUrl.indexOf(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"))>-1) {
				downloadUrl = UriEncoder.encode(downloadUrl);
			}
		}
		downloadUrl = downloadUrl.replace(MemcacheUtil.getDatabaseObj("cos-v4-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
		if (StringUtils.isNotBlank(customSourceUrl)&& !downloadUrl.startsWith(customSourceUrl)) {
			downloadUrl = downloadUrl.replace(downloadUrl.substring(0, downloadUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
		}
		Long end = System.currentTimeMillis();
		logger.info("文件处理中心下载 时间：Run Time: " + (end - start) + "(ms)");
		return "redirect:" + downloadUrl;
	}



	private ResponseMessage returnMessage(ResponseMessage result, String code, String msg, Object data) {
		result.setCode(code);
		result.setMsg(msg);
		result.setData(data);
		return result;
	}











	@RequestMapping(value = "/hjyReadTxt", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage hjyReadTxt() throws Exception{

			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:/importRes.txt")), "UTF-8"));
			JdbcTemplate mysqlJdbc = MysqlSource.getJdbcTemplate();
			String previewUrl = "";
			String updateSql = "update tb_course_res set RES_PREVIEW_URL=?  where fid=? ";
			String fid = null;
			while ((fid = br.readLine()) != null) {
				try {
					String url = "https://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + fid;
					String res = new HttpClient(url).doGet();
					JSONObject j = JSONObject.fromObject(res);
					if ("000000".equals(j.getString("code"))) {
						JSONObject data = j.getJSONObject("data");
						if (StringUtils.isNotBlank(data.getString("previewUrl"))) {
							previewUrl = data.getString("previewUrl");
							mysqlJdbc.update(updateSql, previewUrl, fid);
							System.out.println(fid);
						}
					}
				}catch (Exception e){
					continue;
				}
			}
			br.close();

		ResponseMessage result = new ResponseMessage();
		return returnMessage(result, "000000","成功",null );
	}





	@RequestMapping(value = "/fixRrt", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage fixRrt() throws Exception{

		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:/importRes.txt")), "UTF-8"));
		JdbcTemplate mysqlJdbc = MysqlSource.getJdbcTemplate();
		String previewUrl = "";
		String selectSql = "update tb_course_res set RES_PREVIEW_URL=?  where fid=? ";
		String updateSql = "update tb_course_res set RES_PREVIEW_URL=?  where fid=? ";
		String fid = null;
		while ((fid = br.readLine()) != null) {
			try {
				String url = "https://filecenter.huijiaoyun.com/filecenter/upload/getAttachFileByFid/" + fid;
				String res = new HttpClient(url).doGet();
				JSONObject j = JSONObject.fromObject(res);
				if ("000000".equals(j.getString("code"))) {
					JSONObject data = j.getJSONObject("data");
					if (StringUtils.isNotBlank(data.getString("previewUrl"))) {
						previewUrl = data.getString("previewUrl");
						mysqlJdbc.update(updateSql, previewUrl, fid);
						System.out.println(fid);
					}
				}
			}catch (Exception e){
				continue;
			}
		}
		br.close();

		ResponseMessage result = new ResponseMessage();
		return returnMessage(result, "000000","成功",null );
	}














	public void replacePreviewUrl(Map<String, Object> map, String thumbnailUrl, String previewUrl, String fileExt, String cdnUrl, String customDestUrl, String customSourceUrl, String sourceBucket, String applyType) throws Exception {
		if (Consts.audioList.contains(fileExt) || Consts.videoList.contains(fileExt)) {
			//从es拿到的预览地址不是自定义cdn域名才需要替换
			if (StringUtils.isNotBlank(customDestUrl) && StringUtils.isNotBlank(previewUrl)&& !previewUrl.startsWith(customDestUrl)&&!previewUrl.startsWith(customSourceUrl)) {
				//预览地址包含源码桶，说明文件没有转码，预览地址直接用的原文件下载地址，所以自定义cdn域名要替换为源码桶的
				if(previewUrl.contains(sourceBucket)){
					previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
				}else{
					previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customDestUrl);
				}
				if(StringUtils.isNotBlank(thumbnailUrl)) {
					thumbnailUrl = thumbnailUrl.replace(thumbnailUrl.substring(0, thumbnailUrl.indexOf(cdnUrl) + cdnUrl.length()), customDestUrl);
				}
			}
		} else if (Consts.picList.contains(fileExt) || Consts.movieList.contains(fileExt) || "mp3".equals(fileExt)) {
			if (StringUtils.isNotBlank(customSourceUrl) && StringUtils.isNotBlank(previewUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
			}
		} else if (Consts.docList.contains(fileExt) && "cos".equals(MemcacheUtil.getDatabaseObj(applyType + "-previewVersion"))) {
			if (StringUtils.isNotBlank(customSourceUrl) && StringUtils.isNotBlank(previewUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
			}
		}
		/*else if ("pdf".equals(fileExt) && "3d3080afd6194d5cabef845ebff66829".equals(applyType)) {
			if (StringUtils.isNotBlank(customSourceUrl) && StringUtils.isNotBlank(previewUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
			}
		}*/
		map.put("previewUrl", previewUrl);
		map.put("thumbnailUrl", thumbnailUrl);
	}



	//归档或者取回
	//存储类型DEEP_ARCHIVE，ARCHIVE
	@RequestMapping(value = "/TyyReadTxt", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage TyyReadTxt() throws  Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:/fidlist.txt")), "UTF-8"));
		String fid = null;
		while ((fid = br.readLine()) != null) {
			JSONObject es = EsUtil.searchDoc(fid);
			if(es.isEmpty()){
				continue;
			}
			String filePath = es.getString("filePath");
			String bucketName = es.optString("bucketName");
			//CosUtil.restoreCos(bucketName,filePath);
			CosUtil.copyCos(bucketName,filePath,"STANDARD");
			//es.put("storeType","standard");
			//EsUtil.addOrUpdateDoc(fid,es.toString());
			System.out.println(fid);
		}
		br.close();
		ResponseMessage result = new ResponseMessage();
		return returnMessage(result, "000000", "成功", null);
	}





	@RequestMapping(value = "/fixData", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage fix() throws Exception {
		ResponseMessage result = new ResponseMessage();
		JSONObject es = EsUtil.searchDoc("2676207");
		es.put("userId","admin");
		EsUtil.addOrUpdateDoc("2676207",es.toString());
		return returnMessage(result, "000000", "修复完成", null);
	}




	@RequestMapping(value = "/copyCos", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage copyCosByFid(@RequestBody JSONObject obj) throws Exception{
		ResponseMessage result = new ResponseMessage();

		String fid = obj.optString("fid");
		String fileName = obj.optString("fileName");
		String userId = obj.optString("userId");
		JSONObject es = EsUtil.searchDoc(fid);
		String platformCode = es.getString("platformCode");
		String srcfilePath = es.getString("filePath");
		String srcbucketName = es.optString("bucketName");
		String cosKey = CosUtil.getCosKey(fileName, userId, platformCode);
		AttachFile attach = new AttachFile();
		attach.setUserId(userId);
		attach.setFileName(fileName);
		attach.setFileExt(es.optString("fileExt"));
		attach.setFileLength(es.optLong("fileLength"));
		attach.setFileMd5(es.optString("fileMd5"));
		attach.setApplyType(es.optString("applyType"));
		attach.setSourceType("b49ac4183f1311e9bcfd00fec0a8c9c9");
		attach.setPlatformCode(platformCode);
		attach.setFilePath(cosKey);
		CosUtil.copyCos(srcbucketName,srcfilePath,srcbucketName,cosKey);
		attach = uploadService.finishUploadFile(attach);
		attach.setFidstr(String.valueOf(attach.getFid()));
		return returnMessage(result, "000000","成功",attach );
	}

}
